<template>
  <div class="app-container calendar-list-container">
    <!-- filter 条件查询 -->
    <div class="filter-container">
      <el-input
            clearable
            v-model="listQuery.username"
            :style="searchInputStyle"
            class="filter-item"
            placeholder="请输入员工姓名"
      ></el-input>
      <el-input
            clearable
            v-model="listQuery.jobNumber"
            :style="searchInputStyle"
            class="filter-item"
            placeholder="请输入员工工号"
      ></el-input>
      <el-select filterable clearable @focus="getRole" v-model="listQuery.roleId" :style="searchInputStyle" class="filter-item" placeholder="请选择角色类型" >
        <el-option
          :value="item.roleId"
          :label="item.roleName"
          v-for="(item,index) of this.roleList"
          :key="index"/>
      </el-select>
      <el-input
          clearable
          :style="searchInputStyle"
          v-model="listQuery.phone"
          class="filter-item"
          placeholder="请输入手机号码" >
      </el-input>
      <el-select clearable v-model="listQuery.departmentName" @focus="getDepart" :style="searchInputStyle" class="filter-item" placeholder="请选择员工部门" >
        <el-option
          :value="item"
          :label="item"
          v-for="(item,index) in this.departList"
          :key="index"/>
      </el-select>

      <el-date-picker
        v-model="listQuery.startTime"
        value-format="timestamp"
        format="yyyy-MM-dd"
        placeholder="选择开始日期"
        :style="searchInputStyle" class="filter-item"
      >
      </el-date-picker>
      <el-date-picker
        v-model="listQuery.endTime"
        format="yyyy-MM-dd"
        value-format="timestamp"
        placeholder="选择结束日期"
        :style="searchInputStyle" class="filter-item"
      ></el-date-picker>

      <el-select
        clearable
        v-model="listQuery.status"
        placeholder="请选择状态"
        style="width: 150px;margin-right:15px;"
        class="filter-item">
            <el-option
            :value="item"
            :label="item" v-for="(item,index) in this.statusList"
            :key="index"/>
      </el-select>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="getData">搜索</el-button>
      <el-button class="filter-item" type="success" v-waves @click="QRclick">打印二维码</el-button>
    </div>

    <el-dialog title="打印二维码" :visible.sync="signatureShow" width="40%" center>
        <el-form ref="reviewForm">
          <el-form-item size="small" prop="opinion" label="打印人员" label-width="130px">
            <el-select
                    filterable
                    v-model="countersignOptions"
                    :value-key="'jobNumber'" 
                    multiple
                    placeholder="请选择人员"
                    @change="countersignChange"
                    style="width: 90%;"
                  >
                    <el-option
                      v-for="item,index in userNameList"
                      :key="index"
                      :label="item.userName"
                      :value="item"
                    />
                  </el-select>
          </el-form-item>
        </el-form>
        <div class="qrcode-container" ref="printArea" id="targetDiv">
          <div v-for="(item, index) in countersignOptions" :key="index" class="qrcode-item">
            <div ref="qrCanvas" :id="'qrcode-' + index" class="qrcode-canvas"></div>
            <div>{{ item.userName }}</div>
            <div>{{ item.jobNumber }}</div>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="signatureShow = false" size="mini">取 消</el-button>
          <el-button type="primary" @click="signatureConfirm" size="mini">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog title="打印上岗证" :visible.sync="mountShow" width="40%" center>
        <el-form ref="reviewForm">
          <el-form-item size="small" prop="opinion" label="打印人员" label-width="130px">
            <el-select
                    filterable
                    v-model="countersignOptions"
                    :value-key="'jobNumber'" 
                    multiple
                    placeholder="请选择人员"
                    @change="countersignChange"
                    style="width: 90%;"
                  >
                    <el-option
                      v-for="item,index in userNameList"
                      :key="index"
                      :label="item.userName"
                      :value="item"
                    />
                  </el-select>
          </el-form-item>
          <el-form-item size="small" prop="opinion" label="打印机" label-width="130px">
            <el-select
                clearable
                v-model="printerName" 
                placeholder="请选择打印机"
                @focus="getPrinter"
                >
                <el-option 
                :value="item" 
                :label="item" v-for="(item,index) in printerNameList" 
                :key="index"/>
            </el-select>
          </el-form-item>
        </el-form>
        
        <div slot="footer" class="dialog-footer">
          <el-button @click="mountShow = false" size="mini">取 消</el-button>
          <el-button type="primary" @click="mountConfirm" size="mini">确 定</el-button>
        </div>
      </el-dialog>

    <!-- table 表格 -->
    <el-table :data="tableInfo" v-loading="loadingList" element-loading-text="给我一首歌的时间" stripe border fit highlight-current-row style="width: 100%">
      <el-table-column  label="序号" type="index" align="center" width="80px"/>
      <el-table-column label="员工姓名"  prop="userName"   align="center"/>
      <el-table-column  label="员工工号" prop='jobNumber' align="center" width="100px"/>
      <el-table-column  label="员工角色" prop='roleName' align="center"/>
      <el-table-column  label="员工短号" prop='shortNumber' align="center" width="100px"/>
      <el-table-column  label="手机号码" prop='phone' align="center" width="100px"/>
      <el-table-column  label="隶属工段" prop='sectionNo' align="center" width="100px"/>
      <el-table-column  label="隶属部门"  prop="departmentName" align="center"/>
      <el-table-column  label="组别"  prop="sectionType" align="center"/>
      <el-table-column label="上级领导工号" prop="parentNumber" align="center" width="100px"/>
      <el-table-column label="入职时间" prop="entryTime" align="center"/>
      <el-table-column label="创建时间" prop="createTime" align="center"/>
      <!-- <el-table-column label="员工岗位职级" prop="jobClass" align="center"/>
      <el-table-column label="技能等级" prop="skillRank" align="center"/> -->
      <el-table-column  label="职级" width="100px" align="center">
            <template slot-scope="scope" >  
                  {{ (scope.row.userKnowledgePost ? scope.row.userKnowledgePost.jobTitle : '') + '-' + (scope.row.userKnowledgePost ? scope.row.userKnowledgePost.rankOfPosition == 1 ? '试用级':scope.row.userKnowledgePost.rankOfPosition == 2 ? '初级':scope.row.userKnowledgePost.rankOfPosition == 3 ? '中级':scope.row.userKnowledgePost.rankOfPosition == 4 ? '高级':scope.row.userKnowledgePost.rankOfPosition == 5 ? '师傅级':'':'')}}
            </template>
          </el-table-column>
      <el-table-column label="邮箱" prop="mail" align="center"/>
      <el-table-column label="员工标识" prop="newEmployee" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.newEmployee" size="medium" effect="dark" type="success">新员工</el-tag>
          <el-tag v-else effect="dark" size="medium" type="info">老员工</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="员工状态" prop="status" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status" size="medium" effect="dark" type="success">启用</el-tag>
          <el-tag v-else effect="dark" size="medium" type="info">禁用</el-tag>
        </template>
      </el-table-column>
      <!-- 对员工数据进行编辑与删除操作 -->
      <el-table-column  label="操作"  align="center" width="230" v-if="userInfo.roleId != 37">
        <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handleEdit(scope.row)">修改</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.$index,scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

   <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[5,10, 20, 30, 40, 100, 300, 500]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-divider></el-divider>
    <div>
      <el-button style="margin-right: 10px;" type="success" size="small" @click="hExportExcel" :loading="loadingExcel">导出Excel</el-button>
      <el-button type="success" size="small" @click="getExcelList">下载Excel模板</el-button>
      <el-button class="filter-item" size="small" type="success" v-waves @click="mountClick">打印上岗证</el-button>
      <el-divider></el-divider>
      <el-upload
        class="upload-demo"
        ref="upload"
        :action="action"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :headers="httpHeader"
        :file-list="fileList"
        :auto-upload="false"
         v-if="userInfo.roleId != 37">
        <el-button slot="trigger" size="small" type="primary">选取user文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
        <div slot="tip" class="el-upload__tip">将下载好的文件名为user的Excel表单从此处上传到服务器</div>
      </el-upload>
    </div>

  </div>
</template>


<script>
import { searchWorkers,deleteWorkers,modifyWorkers,getExcelExample} from '@/api/chargingData'
import { getRoleInfo, getDepartInfo, obj_is_null } from '@/utils/publicFun'
import { word04 } from "@/api/knowledgeSkill"

import { findZplPrinterInfoList } from '@/api/orderAndMachine'
import {uploadURL} from '@/utils/baseURL'
import { getToken } from '@/utils/auth'
import mixin from '@/utils/mixin.js'
import QRCode from 'qrcodejs2';
export default {
  name: 'charging_data_list',
  mixins: [mixin],
  data() {
    return {
      url: process.env.ENV,
      action: uploadURL + '/back/user/userExcel',
      total: 0,                                     //数据的总数
      listQuery: {                                  // 搜索信息表单,将该表单信息提交后台查询相关信息
        page: 1,                                    //页码
        limit: 10,                                  //每页显示的数据条数
        startTime:'',                               //开始时间
        endTime:'',                                 //结束时间
        jobNumber:'',                               //员工工号
        roleId:'',                                  //员工角色类型
        username: '',                               //员工姓名
        departmentName:'',                          //员工所属部门
        phone:''                                    //员工手机号码
      },
      roleList: [],                                 // 从服务器调取员工角色信息放入该对象当中
      departList: [],                               // 从后台部门信息放在该对象中
      tableInfo: [],                               // 将接收的用户列表数据进行筛选，只取其中的record数组数据，tableInfo为一个数组
      loadingList: false,                            // 控制table的加载动画
      fileList: [],
      httpHeader: {
          'Authorization': ''
      },
      searchInputStyle: 'width: 150px;margin-right:15px;',
      userInfo: this.$store.state.user.userInfo,
      statusList: ['停用','启用'],
      loadingExcel: false,
      countersignOptions:[],
      signatureShow: false,
      mountShow: false,
      printerName:'',
      printerNameList:[]
    }
  },
  computed: {
     countersignNames() {
      return this.countersignOptions.map(opt => opt.userName).join(',');
    },
     countersignValues() {
      return this.countersignOptions.map(opt => opt.jobNumber).join(',');
    },
  },
  methods: {
    // 获取打印机
    async getPrinter(){
            const data = await findZplPrinterInfoList()
            if(data.code == '1'){
                this.printerNameList = JSON.parse(JSON.stringify(data.data))
                this.printerNameList.forEach((item,index) =>{
                    if(item.indexOf('\\\\')>=0){
                       this.printerNameList[index] = item.split('\\')[3]
                    }
                })
                console.log(this.printerNameList)
            }
        },
    // 打印上岗证
    async mountConfirm(){
      const jobNumberList = this.countersignOptions.map(item => item.jobNumber)
      let query = {
          util:'单',
          printerName: this.printerName,
          jobNumberList: jobNumberList,
      }
      const res = await word04(query)
      if(res.code != 1) return this.$message.error(res.msg)
      this.mountShow = false
    },
    mountClick(){
      this.mountShow = true
    },
    // 打印二维码
    signatureConfirm(){
      if (!this.countersignOptions.length) return console.error('请选择人员!');
      // 生成每个二维码
      this.countersignOptions.forEach((item, index) => {
        // 异步生成二维码（确保DOM已更新）
        this.$nextTick(() => {
          try {
            new QRCode('qrcode-'+ index, {
              text: item.jobNumber,
              width: 100,
              height: 100,
              colorDark: '#000000',
              colorLight: '#ffffff',
              correctLevel: QRCode.CorrectLevel.H
            });
            // 更新生成状态
            // this.$set(this.qrList[index], 'generated', true);
          } catch (error) {
            console.error('生成二维码失败:', error);
          }
        });
      });
      
      setTimeout(() => {
      const targetDiv = document.getElementById('targetDiv');
      if (!targetDiv) {
        alert('未找到需要打印的区域');
        return;
      }
      // // 隐藏不需要打印的元素
      const originalStyles = document.body.getAttribute('style') || '';
      document.body.setAttribute('style', 'overflow:visible');
      document.body.innerHTML = targetDiv.outerHTML
      // this._ensurePrintStylesLoaded()
      // 触发打印
      window.print();
      
      // 恢复页面状态
      document.body.setAttribute('style', originalStyles);
      window.scrollTo(0, scrollTop);
      },1500);
    },
    QRclick(){
      this.signatureShow = true
    },
    countersignChange(){
        },
        transformDat(res) {
      // console.log('%c导出质量系数excel数据:','color:green;font-size:16px;')
      // console.log(res)
      const mapInfo = {
        index:'序号',
        userName: '员工姓名',
        jobNumber: '员工工号',
        jobCategory: '岗位类别',
        roleName: '员工角色',
        shortNumber: '员工短号',
        phone: '手机号码',
        sectionNo: '隶属工段',
        departmentName: '隶属部门',
        sectionType: '组别',
        jobTitle: '所在岗位',
        parentNumber: '上级领导工号',
        entryTime: '入职时间',
        jobClass: '员工岗位职级',
        newEmployee: '员工标识',
        status: '员工状态', 
        mail: '邮箱', 
        tutorUserName: '导师',
      }
      // 对data进行格式化
      // 取出所有的属性名
      const props = Object.keys(res[0]) // ['id','']
      console.log(props)
      // 将属性名从英文转为中文
      const header = props.map(zhkey => mapInfo[zhkey])
      console.log('中文的表头', header)
      // const data=[['xxxx','总裁办'，'13800000']]
      const data = res.map(obj => Object.values(obj))
      console.log(data)
      return { header, data }
    },
    // 导出excel
    async hExportExcel() {
      this.loading = true
      let query = Object.assign({},this.listQuery)
      query.page = 1
      query.limit = 500
      // 导出默认传启用
      query.status = '启用'
      if(query.status) { query.status = this.listQuery.status == '停用'?'0':'1' }
      else { delete query.status }
      console.log('%c导出excel传的参数query:','color:green;font-size:16px;')
      console.log(query)

      this.loadingExcel = true
      let arr = await searchWorkers(query)
      this.loadingExcel = false
      const { header, data } = this.transformDat(this.setSort(arr.data.records))
      import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象
        console.log(excel)
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: '员工excel', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
      this.loading = false
    },
    // 排序函数
    setSort(arr){
      let newArr = JSON.parse(JSON.stringify(arr))
      let arr1 = []
      newArr.forEach((item,index)=>{
        var index2 = index
        let obj = {
          index: index+1,
          userName: item.userName,
          jobNumber: item.jobNumber,
          jobCategory: item.userKnowledgePost ? item.userKnowledgePost.jobCategory:'',
          roleName: item.roleName,
          shortNumber: item.shortNumber,
          phone: item.phone,
          sectionNo: item.sectionNo,
          departmentName: item.departmentName,
          sectionType: item.sectionType,
          jobTitle: item.userKnowledgePost ? item.userKnowledgePost.jobTitle:'',
          parentNumber: item.parentNumber,
          entryTime: item.entryTime,
          jobClass: item.jobClass,
          newEmployee: item.newEmployee?'新员工':'老员工',
          status: item.status?'启用':'禁用',
          mail: item.mail,
          tutorUserName: item.tutorUserName, 
      }
      arr1.push(obj)
      })
      return arr1
    },
    // 下载模板表单
    getExcelList() {
      window.open('http://180.76.113.62:8110/image/portrait/example1.rar')
      },
    submitUpload() {
      // this.httpHeader.Authorization = this.dealCookie(document.cookie)
      this.httpHeader.Authorization = getToken()
      this.$refs.upload.submit()
      },
    // cookies的处理函数
    dealCookie(value) {
        const cookieArr = value.split('=')
        // cookieArr[2]测试服使用
        return cookieArr[1]
    },
    handleRemove(file, fileList) {
        console.log(file, fileList);
      },
    handlePreview(file) {
        console.log(file);
      },
    // 搜索按钮绑定的函数，向服务器发送表单数据
    // 所有传输的表单字段都不是必须的，按需查询
    async handleFilter() {
      this.loadingList = true
      let query = Object.assign({},this.listQuery)
      if(query.status) { query.status = this.listQuery.status == '停用'?'0':'1' }
      else { delete query.status }
      // 用来判断查询的条件是否为空，当不为空时，则返回到第一页
      // 暂时去掉，问题：当条件为空，切换页数为6（任意数）时，再通过选择员工部门查询，查询后的页码还是原来的6，切换页数永远是1。
      // if(obj_is_null(query)) {
		  //   query.page = 1
      // } else {
      //   console.log('搜索内容为空')
      // }
      let { data } = await searchWorkers(query)
      console.log(data)
      this.tableInfo = data.records
      console.log('this.tableInfo',this.tableInfo)
      this.total = data.total
      this.loadingList = false
    },
    // 修改按钮绑定的函数，将整行的内容取好跳转到修改页面
    handleEdit(item) {
      this.$router.push({
        path: 'updateData_List',
        name: 'updateData_List',
        params: item
      })
    },
    // 删除用户按钮,使用elementui的messageBox弹框组件
    // 传入的数据是数据所在的行数以及该条目所有的信息
    handleDelete(index,row) {
      this.$confirm('这将会永久删除该行数据，是否继续?', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(async () => {
          let res = await deleteWorkers({jobNumber: row.jobNumber})
          this.tableInfo.splice(index, 1)
          this.$message({
            type: 'success',
            message: '删除成功'
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 获取部门函数
    async getDepart() {
      const res = await getDepartInfo()
      this.departList = res
    },
    // 获取角色列表函数,当选择器框获得焦点时触发,从服务器调取参数
    async getRole() {
      const res = await getRoleInfo()
      this.roleList = res
    },
    getData(){
      this.listQuery.page = 1
      this.listQuery.limit = 10
      this.handleFilter()
    },
    // table表单下方的页码组件改变每页显示的数据条数
     handleSizeChange(val) {
      this.listQuery.limit = val
      this.handleFilter()
    },
    // table表单下方的页码组件改变页面
     handleCurrentChange(val) {
      this.listQuery.page = val
      this.handleFilter()
    }
  },
  // 进入页面获取table信息
  mounted() {
    this.handleFilter()
    this.focusUserName()
  }
}
</script>

<style>
  .qrcode-container {
    margin-top: 20px;
    display: grid;
    grid-template-columns: repeat(auto-fill, 100px);
    gap: 1cm;
    justify-content: center;
  }
  .qrcode-item {
    width: 100px;
    text-align: center;
  }
  .qrcode-canvas {
  width: 100px;
  height: 100px;
  background-color: #f9f9f9;
  border-radius: 4px;
  margin-bottom: 5px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
